package cn.com.sina.finance.todolist.fragment;

import android.view.View;
import android.widget.EditText;

import com.google.gson.Gson;

import cn.com.sina.finance.todolist.R;
import cn.com.sina.finance.todolist.base.BaseFragment;
import cn.com.sina.finance.todolist.bean.ApiResponse;
import cn.com.sina.finance.todolist.net.HttpCallback;
import cn.com.sina.finance.todolist.net.HttpUtil;
import cn.com.sina.finance.todolist.util.EncodeUtil;
import cn.com.sina.finance.todolist.util.ToastUtil;

/**
 * @author yuebo
 * @date 2024/10/21
 */
public class AddFragment extends BaseFragment {

    private EditText editText;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_add_todo;
    }

    @Override
    public void initView() {
        editText = viewHolder.getView(R.id.editText);
    }

    @Override
    public void initListener() {
        viewHolder.setOnClickListener(R.id.btnOK, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addTodo();
            }
        });
    }

    private void addTodo() {
        String todoContent = editText.getText().toString();
        String url = "http://chenyuebo.cn/addTodo?todo=" + EncodeUtil.urlEncode(todoContent);
        HttpUtil.get(url, new HttpCallback() {
            @Override
            public void onSuccess(String data) {
                ApiResponse response = new Gson().fromJson(data, ApiResponse.class);
                if (response.code == 0) {
                    ToastUtil.showLongToast(getContext(), "添加成功");
                } else {
                    ToastUtil.showLongToast(getContext(), response.msg);
                }
            }

            @Override
            public void onFail(int code, String msg, Throwable e) {
                ToastUtil.showLongToast(getContext(), "网络请求失败" + e.getMessage());
            }
        });
    }
}
